package cn.com.nou.base.service.impl;

import cn.com.nou.base.R;
import cn.com.nou.base.dao.bdm.ColleageEnumerationMapper;
import cn.com.nou.base.dao.bdm.SpecInfoMapper;
import cn.com.nou.base.dao.bdm.StudentInfoMapper;
import cn.com.nou.base.service.SpecInfoService;
import cn.com.nou.base.vo.xuao.SpecInfoListVo;
import cn.com.nou.base.vo.xuao.SpecInfoVo;
import cn.com.nou.common.NouException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SpecInfoServiceImpl implements SpecInfoService {

    @Autowired
    SpecInfoMapper specInfoMapper;

    @Autowired
    ColleageEnumerationMapper colleageEnumerationMapper;

    @Autowired
    StudentInfoMapper studentInfoMapper;

    @Override
    public R addSpecInfo(SpecInfoVo specInfo) {
        specInfo.setSpecId(UUID.randomUUID().toString().replaceAll("-", ""));
        specInfo.setCreateDate(new Date());
        specInfo.setStatusCd(1);
        boolean rs = specInfoMapper.addSpecInfo(specInfo);
        if (rs) {
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R getAllSpecInfo(SpecInfoListVo specInfoListVo) {
        Integer pageNo = Integer.parseInt(specInfoListVo.getPageNo());
        Integer pageSize = Integer.parseInt(specInfoListVo.getPageSize());
        String value = String.valueOf((pageNo - 1) * pageSize);
        if (pageNo != 1) {
            specInfoListVo.setPageNo(value);
        }
        List<SpecInfoVo> list = specInfoMapper.getAllSpecInfo(specInfoListVo);
        return R.ok().put(list);
    }

    @Override
    public R updateSpecInfo(SpecInfoVo specInfoVo) {
        // 查询是否存在存在相同专业代码或专业已经被导入学生信息
        Integer count = studentInfoMapper.getStudentCountBySpecId(specInfoVo.getSpecId());

        // 若存在则不能修改
        if (count > 0) {
            throw new NouException("存在相同专业代码或专业已经被导入学生信息");
        }

        // 存在则修改
        boolean rs = specInfoMapper.updateSpecInfo(specInfoVo);
        if (!rs) {
            throw new NouException("修改失败");
        }
        return R.ok();
    }

    @Override
    public R deleteSpecInfo(String specId) {
        // 判断专业是否已经被院校使用
        int colleageCountBySpecId = colleageEnumerationMapper.getColleageCountBySpecId(specId);

        // 若使用不能删除
        if (colleageCountBySpecId > 0) {
            throw new NouException("专业已经被院校使用");
        }

        // 若未使用则删除
        boolean rs = specInfoMapper.deleteSpecInfo(specId);
        if (!rs) {
            throw new NouException("删除失败");
        }
        return R.ok();
    }
}
